package 力扣题库;

import java.util.*;

public class p350两个数组的交集II {
    public int[] intersect1(int[] nums1, int[] nums2) {
        //哈希表
        Map<Integer,Integer> map=new HashMap<>();
        for (int num:nums1) {
            int count=map.getOrDefault(num,0)+1;
            map.put(num,count);
        }

        List<Integer> list=new ArrayList<>();
        for (int num:nums2) {
            Integer value = map.get(num);
            if (value!=null && value!=0) {
                list.add(num);
                map.put(num,value-1);
            }
        }

        int[] res=new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            res[i]=list.get(i);
        }
        return res;
    }

    public int[] intersect(int[] nums1, int[] nums2) {
        //排序+双指针
        Arrays.sort(nums1);
        Arrays.sort(nums2);

        int len1=nums1.length;
        int len2=nums2.length;

        int index1=0;
        int index2=0;
        int i=0;

        int[] res=new int[Math.min(len1,len2)];

        while (index1<len1 && index2<len2) {
            if (nums1[index1]<nums2[index2]) {
                //谁小，谁向前走一步
                index1++;
            }else if (nums1[index1]>nums2[index2]) {
                //谁小，谁向前走一步
                index2++;
            }else {
                //两个数字一样
                res[i]=nums1[index1];
                i++;
                index1++;
                index2++;
            }
        }

        return Arrays.copyOfRange(res,0,i);
    }
}
